package com.android.happymall.service;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;

import com.android.happymall.model.auction.AuctionActivityData;
import com.android.happymall.model.auction.AuctionBannerData;
import com.android.happymall.model.auction.AuctionResultData;
import com.android.happymall.model.auction.Auction_DetailRecentlyData;
import com.android.happymall.model.auction.Auction_JoinBackData;
import com.android.happymall.model.auction.Auction_NavData;
import com.android.happymall.model.auction.Auction_detail;
import com.android.happymall.utils.ConstantsUrl;
import com.android.happymall.utils.MyLog;
import com.google.gson.Gson;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.security.cert.X509Certificate;

/**
 * Created by Administrator on 2017/10/20.
 */

public class WebSocketService2 extends Service {
    private static WebSocketClient mWebSocketClient;
    private static WebSocketService2 webSocketService;
    private  static SSLSocketFactory factory ;
    private static SSLContext sslContext;
    public static String ACTION_NOT="action_notifyresult2";
    public static String ACTION_BANNER="action_notifybanner2";
    public static String ACTION_Nav="action_nav12";
    public static String ACTION_AUCTION="action_getauctions2";
    public static String ACTION_DETAIL="action_getauction2";
    public static String ACTION_JOINBACK="action_joinback2";
    public static String ACTION_JOINLOG = "action_joinlog2";
    private String address = ConstantsUrl.sockecturl;
    private String pong ="{\"type\":\"pong\"}";
    private Boolean isRunning = true;
    private Boolean isConnecting = false;
    private Boolean isFirstPing = true;
    private static String cid;
    private AuctionResultData auctionResultData = new AuctionResultData();
    private AuctionBannerData bannerData = new AuctionBannerData();
    private Auction_detail auction_detail = new Auction_detail();
    private Auction_NavData navData = new Auction_NavData();
    private AuctionActivityData auctionActivityData = new AuctionActivityData();
    private Auction_JoinBackData auction_joinBackData = new Auction_JoinBackData();
    private Auction_DetailRecentlyData recentlyData = new Auction_DetailRecentlyData();
    public static WebSocketService2 getInstance() {
        if(webSocketService==null)
        {
            return new WebSocketService2();
        }
        return webSocketService;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        try {
            initSocketClient();
        }
        catch (URISyntaxException e)
        {
            e.printStackTrace();
        }
        connect();
        return START_STICKY;
    }
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }
    //初始化websocket
    private void initSocketClient() throws URISyntaxException {
        if(mWebSocketClient == null) {
            mWebSocketClient = new WebSocketClient(new URI(address)) {
                @Override
                public void onOpen(ServerHandshake serverHandshake) {
                    //连接成功
                    isConnecting = true;
                }


                @Override
                public void onMessage(String s) {
                    //服务端消息
                    try {
                        JSONObject obj = new JSONObject(s);
                        String type = obj.getString("type");
                        switch (type) {
                            case "ping":
                                if (isFirstPing) {
                                    isFirstPing = false;
                                    Palpitationconnect();
                                }
                                break;
                            case "auction_result":
                                MyLog.e("auction_result", s);
                                auctionResultData = new Gson().fromJson(s, AuctionResultData.class);
                                Intent mIntent = new Intent(ACTION_NOT);
                                Bundle bundle = new Bundle();
                                bundle.putSerializable("AuctionResult", auctionResultData);
                                mIntent.putExtra("bundle", bundle);
                                sendBroadcast(mIntent);
                                break;

                            case "get_banner":
                                bannerData = new Gson().fromJson(s, AuctionBannerData.class);
                                Intent Intent1 = new Intent(ACTION_BANNER);
                                Bundle bundle1 = new Bundle();
                                bundle1.putSerializable("AuctionBanner", bannerData);
                                Intent1.putExtra("bundle1", bundle1);
                                sendBroadcast(Intent1);
                                break;
                            case "get_auctions":
                                MyLog.e("get_auctions", s);
                                auctionActivityData = new Gson().fromJson(s, AuctionActivityData.class);
                                Intent Intent2 = new Intent(ACTION_AUCTION);
                                Bundle bundle2 = new Bundle();
                                bundle2.putSerializable("AuctionGetAuctions", auctionActivityData);
                                bundle2.putString("AuctionGetAuctionsCid", cid);
                                Intent2.putExtra("bundle2", bundle2);
                                sendBroadcast(Intent2);
                                break;
                            case "get_auction":
                                MyLog.e("get_auction", s);
                                auction_detail = new Gson().fromJson(s, Auction_detail.class);
                                Intent Intent4 = new Intent(ACTION_DETAIL);
                                Bundle bundle4 = new Bundle();
                                bundle4.putSerializable("AuctionGetAuction", auction_detail);
                                Intent4.putExtra("bundle4", bundle4);
                                sendBroadcast(Intent4);
                                break;
                            case "join_auction":
                                MyLog.e("join_auction", s);
                                auction_joinBackData = new Gson().fromJson(s, Auction_JoinBackData.class);
                                Intent Intent3 = new Intent(ACTION_JOINBACK);
                                Bundle bundle3 = new Bundle();
                                bundle3.putSerializable("AuctionJoinBack", auction_joinBackData);
                                Intent3.putExtra("bundle3", bundle3);
                                sendBroadcast(Intent3);
                                break;
                            case "join_log":
                                MyLog.e("join_log", s);
                                recentlyData = new Gson().fromJson(s, Auction_DetailRecentlyData.class);
                                Intent Intent5 = new Intent(ACTION_JOINLOG);
                                Bundle bundle5 = new Bundle();
                                bundle5.putSerializable("AuctionJoinLog", recentlyData);
                                Intent5.putExtra("bundle5", bundle5);
                                sendBroadcast(Intent5);
                                break;
                            case "get_menus":
                                MyLog.e("menus", s);
                                navData = new Gson().fromJson(s, Auction_NavData.class);
                                Intent Intent6 = new Intent(ACTION_Nav);
                                Bundle bundle6 = new Bundle();
                                bundle6.putSerializable("AuctionNav", navData);
                                Intent6.putExtra("bundle6", bundle6);
                                sendBroadcast(Intent6);
                                break;
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }


                @Override
                public void onClose(int i, String s, boolean remote) {
                    //连接断开，remote判定是客户端断开还是服务端断开
                    isConnecting=false;
                    closeConnect();
                    mWebSocketClient = null;
                    ReConnect();

                }


                @Override
                public void onError(Exception e) {
                    isConnecting=false;
                    mWebSocketClient = null;
                    ReConnect();
                }
            };
        }
        //TODO
        httpsMethod1();//https连接时用到，http连接时注释
    }

    private void httpsMethod1() {
        sslContext = null;
        try {
            sslContext = SSLContext.getInstance("TLS");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        try {
            sslContext.init(null, new TrustManager[] {
                    new X509TrustManager() {

                        public void checkClientTrusted(X509Certificate[] certs, String authType) {
                            System.out.println("checkClientTrusted1");
                        }

                        @Override
                        public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                                throws CertificateException {
                            System.out.println("checkClientTrusted2");
                        }

                        public void checkServerTrusted(X509Certificate[] certs,
                                                       String authType) {
                            System.out.println("checkServerTrusted1");
                        }

                        @Override
                        public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                                throws CertificateException {
                            System.out.println("checkServerTrusted2");
                        }
                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return null;
                        }
                    }
            }, new SecureRandom());
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
    }

    //断开重连或者未连接上重连
    private void   ReConnect() {
        try {
            while(!isConnecting) {
                initSocketClient();
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }


    //心跳维持长连接
    private void  Palpitationconnect() {
        new Thread(){
            @Override
            public void run() {
                try {
                    while(isRunning) {
                        Thread.sleep(30000);
                        sendMsg(pong);

                    }
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }

            }
        }.start();
    }

    //连接
    public static void connect() {
        new Thread(){
            @Override
            public void run() {
                //TODO
                httpMethod2();//https连接时用到，http连接时注释
                mWebSocketClient.connect();
            }
        }.start();
    }

    private static void httpMethod2() {
        factory = sslContext.getSocketFactory();
        try {
            mWebSocketClient.setSocket(factory.createSocket());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //断开连接
    private void closeConnect() {
        try {
            mWebSocketClient.close();
        }
        catch(Exception e) {
            e.printStackTrace();
        }
        finally {
            mWebSocketClient = null;
        }
    }

    //发送消息
    /**
     *
     */
    public static void sendMsg(String msg) {
        try {
            mWebSocketClient.send(msg);
        }catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    //设置发送的商品分类号
    /**
     *
     */
    public static void setCid(String id) {
        cid = id;
    }
}
